package com.example.myapplication.ui.clock;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.example.myapplication.AnalogClockView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.os.Handler;
import android.os.Looper;
import com.example.myapplication.R;

public class ClockFragment extends Fragment {
    private AnalogClockView analogClockView;
    private TextView digitalClockView;
    private Handler handler;
    private Runnable updateTimeRunnable;

    public ClockFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_clock, container, false);

        analogClockView = view.findViewById(R.id.analog_clock);
        digitalClockView = view.findViewById(R.id.digital_clock);

        // 初始化Handler和Runnable来更新时间
        handler = new Handler();
        updateTimeRunnable = new Runnable() {
            @Override
            public void run() {
                updateTime();
                handler.postDelayed(this, 1000);
            }
        };

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 开始更新时间
        handler.post(updateTimeRunnable);
    }

    @Override
    public void onPause() {
        super.onPause();
        // 停止更新时间
        handler.removeCallbacks(updateTimeRunnable);
    }

    private void updateTime() {
        // 更新电子时钟
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 设置为北京时间
        String currentTime = sdf.format(new Date());
        digitalClockView.setText(currentTime);

        // 模拟时钟会自动重绘
    }
}